package com.offcn.user.controller;

import com.offcn.common.response.AppResponse;
import com.offcn.user.component.SmsTemplate;
import com.offcn.user.pojo.TMember;
import com.offcn.user.pojo.TMemberAddress;
import com.offcn.user.service.UserService;
import com.offcn.user.vo.req.UserRegisterVo;
import com.offcn.user.vo.resp.UserRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户模块，完成用户的注册，登录，获取验证码")
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @ApiOperation("获取验证码")
    @PostMapping("/sendSms")
    public AppResponse<Object> sendSms(String mobile){
        // 创建一个验证码
        String code = UUID.randomUUID().toString().substring(0, 4);
        // 存储验证码
        redisTemplate.opsForValue().set(mobile,code,5, TimeUnit.MINUTES);
        // 发送短信
        String sendResponse = smsTemplate.sendSms(mobile, code);
        if(sendResponse == null || sendResponse.equals("fail")){
            return AppResponse.fail("短信发送失败");
        }
        return AppResponse.ok(sendResponse);
    }

    @PostMapping("/register")
    public AppResponse<Object> register(UserRegisterVo member){
        // 验证码验证
        // 从redis中获取验证码
        String code = redisTemplate.opsForValue().get(member.getLoginacct());
        // 验证码不为空
        if(!StringUtils.isEmpty(code)){
            // 比较和用户提交的验证码是否相同
           if(!code.equals(member.getCode())){
               return AppResponse.fail("验证码错误");
           }
            TMember tMember = new TMember();
            // 复制属性值的条件是 要求两个对象的属性名要一致
            BeanUtils.copyProperties(member,tMember);
            try {
                userService.registerUser(tMember);
                return AppResponse.ok("注册成功");
            } catch (Exception e) {
                e.printStackTrace();
                return AppResponse.fail(e.getMessage());
            }

        }else{
            return AppResponse.fail("验证码已经失效");
        }

    }

    @PostMapping("/login")
    public AppResponse<UserRespVo> login(String loginacct,String userpswd){
        TMember member = userService.login(loginacct, userpswd);
        if(member == null){
            AppResponse resp = AppResponse.fail(null);
            resp.setMsg("用户名或密码错误");
            return resp;
        }
        // 登录成功
        // 创建令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        UserRespVo respVo = new UserRespVo();
        respVo.setAccessToken(token);
        BeanUtils.copyProperties(member,respVo);
        // 在redis中存储令牌 ，将来验证令牌是否有效
        // 键  令牌   ==>  值   用户ID
        redisTemplate.opsForValue().set(token,member.getId().toString(),2,TimeUnit.HOURS);
        return AppResponse.ok(respVo);
    }

    @GetMapping("/getUser/{id}")
    public AppResponse<UserRespVo> getUserById(@PathVariable("id") Integer id){

        TMember member = userService.getTMemberById(id);
        UserRespVo userRespVo = new UserRespVo();
        BeanUtils.copyProperties(member,userRespVo);
        return AppResponse.ok(userRespVo);
    }

    @GetMapping("/getAddress/{accessToken}")
    public AppResponse<List<TMemberAddress>> getAddressList(@PathVariable("accessToken") String accessToken){
        String memberIdStr = redisTemplate.opsForValue().get(accessToken);
        if(memberIdStr == null){
            AppResponse<List<TMemberAddress>> fail = AppResponse.fail(null);
            fail.setMsg("用户没有登录");
            return fail;
        }
        List<TMemberAddress> addressList = userService.getAddresList(Integer.parseInt(memberIdStr));
        return AppResponse.ok(addressList);

    }
}
